<template>
  <lay-layer v-model="visible" :title="layer_title" :area="['800px', '500px']" :shadeClose="shadeClose" :maxmin="true"
    :moveOut="true" :resize="true" closeBtn="1" :end="end" :close="close" :beforeClose="beforeClose">
    <lay-form :loading="loading" size="sm">
      <div style="padding:10px 10px 0px 10px;margin: 0px;">
        <lay-form-item style="text-align: left;padding:0px;margin: 0px;">
          <!-- <lay-button size="sm" @click="original" v-show="http_r_p == 'up'">还原</lay-button> -->
          <lay-button size="sm" type="primary" @click="submit">提交</lay-button>
        </lay-form-item>
      </div>

      <lay-tab type="card" v-model="laytabvmodel">
        <lay-tab-item title="基础信息" id="1">
          <div style="padding:0px 10px 0px 10px;">
            <lay-form :model="mainForm" :rules="rules" ref="mainFormRef" required>
              <lay-row>
                <lay-col :md="12">
                  <lay-form-item label="货商名称" prop="name">
                    <lay-input v-model="mainForm.name" placeholder="请输入货商名称"></lay-input>
                  </lay-form-item>
                </lay-col>
                <lay-col :md="12">
                  <lay-form-item label="负责人" prop="principal">
                    <lay-input v-model="mainForm.principal" placeholder="请输入负责人"></lay-input>
                  </lay-form-item>
                </lay-col>
              </lay-row>
              <lay-row>
                <lay-col :md="12">
                  <lay-form-item label="电话" prop="tel">
                    <lay-input v-model="mainForm.tel" placeholder="请输入电话，如xxx-xxxxxxxx"></lay-input>
                  </lay-form-item>
                </lay-col>
                <lay-col :md="12">
                  <lay-form-item label="手机号" prop="mobile">
                    <lay-input v-model="mainForm.mobile" placeholder="请输入手机号"></lay-input>
                  </lay-form-item>
                </lay-col>
              </lay-row>
              <lay-row>
                <lay-col :md="12">
                  <lay-form-item label="传真" prop="fax">
                    <lay-input v-model="mainForm.fax" placeholder="请输入传真"></lay-input>
                  </lay-form-item>
                </lay-col>
                <lay-col :md="12">
                  <lay-form-item label="邮箱" prop="email">
                    <lay-input v-model="mainForm.email" placeholder="请输入邮箱"></lay-input>
                  </lay-form-item>
                </lay-col>
              </lay-row>
              <lay-row>
                <lay-col :md="12">
                  <lay-form-item label="开户银行" prop="bank_acctno">
                    <lay-input v-model="mainForm.bank_acctno" placeholder="请输入开户银行"></lay-input>
                  </lay-form-item>
                </lay-col>
                <lay-col :md="12">
                  <lay-form-item label="银行账号" prop="bank_no">
                    <lay-input v-model="mainForm.bank_no" placeholder="请输入银行账号"></lay-input>
                  </lay-form-item>
                </lay-col>
              </lay-row>
              <lay-row>
                <lay-col :md="12">
                  <lay-form-item label="地址" prop="addr">
                    <lay-input v-model="mainForm.addr" placeholder="请输入地址"></lay-input>
                  </lay-form-item>
                </lay-col>
                <lay-col :md="12">
                  <lay-form-item label="备注">
                    <lay-input v-model="mainForm.memo" placeholder="请输入备注"></lay-input>
                  </lay-form-item>
                </lay-col>
              </lay-row>
            </lay-form>
          </div>
        </lay-tab-item>

        <lay-tab-item title="货商附加信息" id="2">
          <div style="padding:0px 10px 0px 10px;">
            <lay-table :columns="supAddrColums" :data-source="supAddrForm" even>
              <template #name="{ row }">
                <lay-input v-model="row.name" placeholder="请输入货商名称" />
              </template>
              <template #principal="{ row }">
                <lay-input v-model="row.principal" placeholder="请输入负责人" />
              </template>
              <template #tel="{ row }">
                <lay-input v-model="row.tel" @blur="verifyMethod('tel', row.tel)" placeholder="如xxx-xxxxxxxx" />
              </template>
              <template #mobile="{ row }">
                <lay-input v-model="row.mobile" @blur="verifyMethod('mobile', row.mobile)" placeholder="请输入手机号" />
              </template>
              <template #fax="{ row }">
                <lay-input v-model="row.fax" placeholder="请输入传真" />
              </template>
              <template #email="{ row }">
                <lay-input v-model="row.email" @blur="verifyMethod('email', row.email)" placeholder="请输入邮箱" />
              </template>
              <template #addr="{ row }">
                <lay-input v-model="row.addr" placeholder="请输入地址" />
              </template>
              <template #memo="{ row }">
                <lay-input v-model="row.memo" placeholder="请输入备注" />
              </template>
              <template v-slot:operator="{ row, rowIndex }">
                <lay-button type="danger" size="md" @click="deleteRow('supAddrForm', rowIndex)">删除</lay-button>
              </template>
            </lay-table>
            <lay-button border="green" border-style="dashed" :fluid="true" @click="addRow('supAddrForm')" style="margin-top: 10px">新增</lay-button>
          </div>
        </lay-tab-item>

        <lay-tab-item title="银行附加信息" id="3">
          <div style="padding:0px 10px 0px 10px;">
            <lay-table :columns="supBankColums" :data-source="supBankForm" even>
              <template #name="{ row }">
                <lay-input v-model="row.name" placeholder="请输入货商名称" />
              </template>
              <template #bank_acctno="{ row }">
                <lay-input v-model="row.bank_acctno" placeholder="请输入开户银行" />
              </template>
              <template #bank_no="{ row }">
                <lay-input v-model="row.bank_no" placeholder="请输入银行账号" />
              </template>
              <template #memo="{ row }">
                <lay-input v-model="row.memo" placeholder="请输入备注" />
              </template>
              <template v-slot:operator="{ row, rowIndex }">
                <lay-button type="danger" size="md" @click="deleteRow('supBankForm', rowIndex)">删除</lay-button>
              </template>
            </lay-table>
            <lay-button border="green" border-style="dashed" :fluid="true" @click="addRow('supBankForm')" style="margin-top: 10px">新增</lay-button>
          </div>
        </lay-tab-item>
      </lay-tab>
    </lay-form>
  </lay-layer>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { layer } from '@layui/layui-vue';
// import { toJSONString, random } from 'xe-utils';
import { number } from 'echarts';
import { supNew, supUp } from "../../../../api/module/user"; //请求模块

// const props = defineProps(['upbd']);
// const emit = defineEmits(['update:upbd', 'topClick']);
const emit = defineEmits(['topClick']);
const layer_title = ref('新增');//弹窗标题
const shadeClose = ref(true);//遮盖层关闭
const http_r_p = ref('up');//新增还是修改
const visible = ref(false);// 弹窗显示
const mainFormRef = ref();

const laytabvmodel = ref("1")
// 表单字段
const mainForm = ref({
  name: "", //"货商名称:字符串",
  principal: "", //"默认负责人:字符串",
  tel: "",//"默认电话:字符串",
  mobile: "", //"默认手机:字符串",
  fax: "", //"默认传真:字符串",
  email: "", //"默认电子邮箱:字符串",
  bank_acctno: "", // "默认开户银行:字符串",
  bank_no: "", //"默认银行账号:字符串",
  addr: "", //"默认地址:字符串",
  memo: "" //"备注:字符串"
});

const supAddrColums = ref([
  {
    title: "名称",
    key: "name",
    customSlot: "name",
    align: "center",
    width: "120px",
  },
  {
    title: "负责人",
    key: "principal",
    customSlot: "principal",
    align: "center",
    width: "120px",
  },
  {
    title: "联系电话",
    key: "tel",
    customSlot: "tel",
    align: "center",
    width: "120px",
  },
  {
    title: "手机",
    key: "mobile",
    customSlot: "mobile",
    align: "center",
    width: "120px",
  },
  {
    title: "传真",
    key: "fax",
    customSlot: "fax",
    align: "center",
    width: "120px",
  },
  {
    title: "默认电子邮箱",
    key: "email",
    customSlot: "email",
    align: "center",
    width: "140px",
  },
  {
    title: "地址",
    key: "addr",
    customSlot: "addr",
    align: "center",
    width: "120px",
  },
  {
    title: "备注",
    key: "memo",
    customSlot: "memo",
    align: "center",
    width: "120px",
  },
  { 
    title:"操作", 
    width: "80px", 
    customSlot:"operator", 
    key:"operator", 
    fixed: "right", 
    ignoreExport: true 
  }
])

const supAddrForm = ref([{
  name: "", //"名称",
  principal: "", //"负责人",
  tel: "", //"联系电话",
  mobile: "", //"手机",
  fax: "", //"传真",
  email: "", //"默认电子邮箱",
  addr: "", //"地址",
  memo: "" //"备注"
}])

const supBankColums = ref([
  {
    title: "名称",
    key: "name",
    customSlot: "name",
    align: "center",
    width: "120px",
  },
  {
    title: "开户银行",
    key: "bank_acctno",
    customSlot: "bank_acctno",
    align: "center",
    width: "220px",
  },
  {
    title: "银行账号",
    key: "bank_no",
    customSlot: "bank_no",
    align: "center",
    width: "180px",
  },
  {
    title: "备注",
    key: "memo",
    customSlot: "memo",
    align: "center",
    width: "120px",
  },
  { 
    title:"操作", 
    width: "80px", 
    customSlot:"operator", 
    key:"operator", 
    fixed: "right", 
    ignoreExport: true 
  }
])
const supBankForm = ref([
  {
    name: "", //"名称",
    bank_acctno: "", // "默认开户银行:字符串",
    bank_no: "", //"默认银行账号:字符串",
    memo: "" //"备注:字符串"
  }
])

const rules = ref({
  // mobile: {
  //   validator(rule: any, value: string, callback: (arg0: Error) => void, source: any, options: any) {
  //     //手机号
  //     const reg = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/;
  //     if (!reg.test(value)) {
  //       callback(new Error(`请输入正确的手机号`));
  //     } else {
  //       return true;
  //     }
  //   }
  // },
  // tel: {
  //   validator(rule: any, value: string, callback: (arg0: Error) => void, source: any, options: any) {
  //     //座机
  //     const reg = /^(?:(?:\d{3}-)?\d{8}|^(?:\d{4}-)?\d{7,8})(?:-\d+)?$/;
  //     if (!reg.test(value)) {
  //       callback(new Error(`请输入正确的座机号`));
  //     } else {
  //       return true;
  //     }
  //   }
  // },
  // email: {
  //   type: 'email',
  // },
})

const loading = ref(false)

const validateFlag = ref(true) //验证开关

const form = reactive({});//缓存旧数据为还原表单做准备

//子组件方法
const childFun = (op: string, data: any) => {
  // op='up'//修改模式 new 新增
  visible.value = !visible.value;
  if (op == 'up') {
    http_r_p.value = 'up';//新增还是修改
    layer_title.value = '修改';//弹窗标题
    shadeClose.value = true;//遮盖层关闭
    console.log('update:', data)
    mainForm.value = data
    supAddrForm.value = data.all_sup_addr
    supBankForm.value = data.all_sup_bank
    // modelForm.value = data;//把上级行数据填到窗口中

    // Object.assign(form, { ...data });
  } else {
    http_r_p.value = 'new';//新增还是修改
    layer_title.value = '新增';//弹窗标题
    shadeClose.value = false;//遮盖层关闭
    mainForm.value = {
      name: "", //"货商名称:字符串",
      principal: "", //"默认负责人:字符串",
      tel: "",//"默认电话:字符串",
      mobile: "", //"默认手机:字符串",
      fax: "", //"默认传真:字符串",
      email: "", //"默认电子邮箱:字符串",
      bank_acctno: "", // "默认开户银行:字符串",
      bank_no: "", //"默认银行账号:字符串",
      addr: "", //"默认地址:字符串",
      memo: "" //"备注:字符串"
    }
    supAddrForm.value = [{
      name: "", //"名称",
      principal: "", //"负责人",
      tel: "", //"联系电话",
      mobile: "", //"手机",
      fax: "", //"传真",
      email: "", //"默认电子邮箱",
      addr: "", //"地址",
      memo: "" //"备注"
    }]
    supBankForm.value = [{
      name: "", //"名称",
      bank_acctno: "", // "默认开户银行:字符串",
      bank_no: "", //"默认银行账号:字符串",
      memo: "" //"备注:字符串"
    }]
  }
};

const addRow = (key: string) => {
  if (key == 'supBankForm') {
    supBankForm.value.push({
      name: "", //"名称",
      bank_acctno: "", // "默认开户银行:字符串",
      bank_no: "", //"默认银行账号:字符串",
      memo: "" //"备注:字符串"
    })
  } else if (key == 'supAddrForm') {
    supAddrForm.value.push({
      name: "", //"名称",
      principal: "", //"负责人",
      tel: "", //"联系电话",
      mobile: "", //"手机",
      fax: "", //"传真",
      email: "", //"默认电子邮箱",
      addr: "", //"地址",
      memo: "" //"备注"
    })
  }
}

const deleteRow = (key: string, index: number) => {
  console.log(key, index)
  if (key == 'supAddrForm') {
    supAddrForm.value.splice(index, 1)
  } else if (key == 'supBankForm') {
    supBankForm.value.splice(index, 1)
  }
}

const verifyMethod = (key: string, val: any) => {
  console.log(key, val)
  let reg = null
  switch (key) {
    case 'tel':
      reg = /^(?:(?:\d{3}-)?\d{8}|^(?:\d{4}-)?\d{7,8})(?:-\d+)?$/;
      break;
    case 'mobile':
      reg = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/;
      break;
    case 'email':
      reg = /^[A-Za-z0-9._%-]+@([A-Za-z0-9-]+\.)+[A-Za-z]{2,4}$/;
      break;
    default:
      break;
  }

  if (!(reg && reg.test(val))) {
    layer.msg("请输入正确的数据", { icon : 5, time: 1000})
    validateFlag.value = false
  } else {
    validateFlag.value = true
  }
}

// 原始数据
const original = () => {
  // Object.assign(modelForm.value, { ...form }); 
};
// 清空表单
const reset = () => { mainFormRef.value.reset(); };
// 清除校验
const clearValidate = () => { mainFormRef.value.clearValidate(); };
// 窗口销毁
const end = () => { };
// 窗口关闭
const close = () => { };
// 窗口关闭前置
const beforeClose = () => { original(); };
// 提交表单
const submit = function () {
  mainFormRef.value.validate(
    (isValidate: any, model: any, errors: any) => {
      console.log("model", model)
      if (isValidate && validateFlag.value) {
        http_r('new');
      } else {
        layer.msg("填报数据有误，请检查！", { icon : 5, time: 1000})
      }
    });
}
// HTTP请求
const http_r = async (op: string) => {
  const params = {
    main: mainForm.value,
    all_sup_addr: supAddrForm.value,
    all_sup_bank: supBankForm.value
  }
  loading.value = true
  //新增还是修改
  if (http_r_p.value == 'up') {
    let data = await supUp(params);//HTTP
    console.log(data);
    loading.value = false
    if (data.code == 200) {
      layer.msg(data.msg, { icon: 1 }, async () => {
        emit('topClick', '父组件事件');
        reset()
        visible.value = !visible.value;
      });
    } else {
      layer.msg(data.msg, { icon: 2 });
    }
  } else if (http_r_p.value == 'new') {
    let data = await supNew(params);//HTTP
    loading.value = false
    if (data.code == 200) {
      layer.msg(data.msg, { icon: 1 }, async () => {
        emit('topClick', '父组件事件');
        reset()
        visible.value = !visible.value;
      });
    } else {
      layer.msg(data.msg, { icon: 2 });
    }
  } else { }

};


//向父组件暴露子组件的方法或者数据
defineExpose({ childFun, });
</script>

<style lang="less" scoped>
.myCard :deep(.layui-card-header) {
  text-align: end;
}
</style>